package top.wshape1.shiziapi.uaa.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.DefaultRedirectStrategy;
import top.wshape1.shiziapi.common.constant.AuthConstant;
import top.wshape1.shiziapi.common.constant.BizCodeEnum;
import top.wshape1.shiziapi.common.exception.CustomException;
import top.wshape1.shiziapi.common.utils.R;
import top.wshape1.shiziapi.uaa.domain.User;
import top.wshape1.shiziapi.uaa.utils.ResponseUtil;
import top.wshape1.shiziapi.uaa.utils.UserUtil;

import java.io.IOException;

/**
 * @author Wshape1
 * @version 1.0
 * @description 修改DefaultRedirectStrategy实现自定义转发
 * @since 2023-08-30
 */

public class MyRedirectStrategy extends DefaultRedirectStrategy {


    @Override
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {

        // 对绑定的进行校验
        String userEncoded = request.getHeader(AuthConstant.HEADER_PAYLOAD_NAME);
        if (userEncoded != null) {
//            进行绑定操作 校验用户信息
            User user = UserUtil.getFromEncodedString(userEncoded);

            String[] split = request.getServletPath().split("/");
            String regId = split[split.length - 1];

            if (("gitee".equalsIgnoreCase(regId) && user.getGiteeId() != null) ||
                    ("github".equalsIgnoreCase(regId) && user.getGithubId() != null))
                throw new CustomException(R.instance(BizCodeEnum.EXIST_BINDING_ERROR));
        }

        // 正常流程

        String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
        redirectUrl = response.encodeRedirectURL(redirectUrl);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug(LogMessage.format("Sending a message including redirect url to %s", redirectUrl));
        }

        R<String> r = R.ok();
        r.setData(redirectUrl);
        ResponseUtil.writeResponse(response, r);

    }
}
